<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!--卡片视图-->
    <el-card class="box-card">
      <el-row :gutter="20"
              class="box-card_head">
        <el-col :span="8">
          <!--搜索框-->
          <el-input placeholder="请输入内容"
                    v-model="queryInfo.query"
                    clearable
                    @clear="getUserList">
            <el-button slot="append"
                       icon="el-icon-search"
                       @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary"
                     @click="addDialogVisble=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--添加用户对话框-->
      <!--visible.sync  设置对话框显示或隐藏-->
      <!--@Close  当对话框关闭时，清除验证-->
      <el-dialog title="添加用户"
                 :visible.sync="addDialogVisble"
                 width="30%"
                 @close="addDialogClosed">
        <!--内容主体区域-->
        <el-form ref="addFormRef"
                 :rules="addFormRules"
                 :model="addForm"
                 label-width="80px">
          <el-form-item label="用户名"
                        prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="密码"
                        prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop="phone">
            <el-input v-model="addForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="角色"
                        prop="roleId">
            <el-select v-model="addForm.roleId"
                       placeholder="请选择">
              <el-option v-for="item in roleIdList"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!--内容底部区域-->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="addDialogVisble = false">取 消</el-button>
          <el-button type="primary"
                     @click="addUses">确 定</el-button>
        </span>
      </el-dialog>
      <!--修改用户对话框-->
      <!--visible.sync  设置对话框显示或隐藏-->
      <!--@Close  当对话框关闭时，清除验证-->
      <el-dialog title="修改用户"
                 :visible.sync="editDialogVisible"
                 width="40%"
                 @close="editDialogClosed">
        <!--内容主体区域-->
        <el-form ref="editFormRef"
                 :rules="addFormRules"
                 :model="editForm"
                 label-width="80px">
          <el-form-item label="用户名"
                        prop="name">
            <el-input v-model="editForm.name"
                      disabled></el-input>
          </el-form-item>
          <el-form-item label="手机"
                        prop="phone">
            <el-input v-model="editForm.phone"></el-input>
          </el-form-item>
          <el-form-item label="角色分配"
                        prop="mobile">
            <el-select v-model="editRoldName"
                       placeholder="请选择">
              <el-option v-for="item in roleIdList"
                         :key="item.value"
                         :label="item.name"
                         :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!--内容底部区域-->
        <span slot="footer"
              class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary"
                     @click="editUser()">确 定</el-button>
        </span>
      </el-dialog>

      <!--用户列表区域-->
      <el-table :data="userList"
                border
                stripe
                :header-cell-style="{textAlign: 'center'}"
                :cell-style="{ textAlign: 'center' }">
        <el-table-column type="index"
                         label="#"></el-table-column>
        <el-table-column label="用户名"
                         prop="name"></el-table-column>
        <el-table-column label="电话"
                         prop="phone"></el-table-column>
        <el-table-column label="微信小程序"
                         prop="wxName">
          <template slot-scope="scope">
            <el-tag type="warning"
                    v-if="scope.row.wxName == null"
                    v-model="scope.row.wxName">未绑定小程序</el-tag>
            <el-tag type="success"
                    v-else
                    v-model="scope.row.openid">{{scope.row.wxName}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="角色"
                         prop="roleId">
          <template slot-scope="scope">
            <span v-if="scope.row.roleId == 999">超级管理员</span>
            <span v-else-if="scope.row.roleId == 888">管理员</span>
            <span v-else-if="scope.row.roleId == 1">普通用户</span>
            <span v-else-if="scope.row.roleId == 2">维修人员</span>
          </template>
        </el-table-column>
        <el-table-column label="状态"
                         prop="state">
          <template slot-scope="scope">
            <!-- {{scope.row}} -->
            <el-switch :active-value="1"
                       :inactive-value="0"
                       v-model="scope.row.state"
                       @change="setting_state(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作"
                         width="180px">
          <template slot-scope="scope">
            <!--修改按钮-->
            <el-button type="primary"
                       icon="el-icon-edit"
                       size="mini"
                       @click="showeditDialog(scope.row.id)"></el-button>
            <!--删除按钮-->
            <el-button type="danger"
                       icon="el-icon-delete"
                       size="mini"
                       @click="deleteuser(scope.row.id)"></el-button>
            <!--重置密码按钮-->
            <el-tooltip :enterable="false"
                        effect="dark"
                        content="重置密码"
                        placement="top">
              <el-button type="success"
                         icon="el-icon-refresh"
                         size="mini"
                         @click="setPwd(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!--分页-->
      <!--@size-change  每页显示的条数，每次更改需要触发的函数-->
      <!--@current-change 更改页码时触发的函数-->
      <!--current-page  当前显示第几页-->
      <!--page-sizes 设置每页显示条数-->
      <!--page-size  当前每页显示多少条-->
      <el-pagination @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :current-page="queryInfo.pagenum"
                     :page-sizes="[ 3, 5, 8, 10]"
                     :page-size="queryInfo.pagesize"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total"></el-pagination>
    </el-card>
  </div>
</template>
<script>
import {
  getAllUser,
  modify,
  register,
  getInfo,
  deleteUser,
} from '@/api/user.js'
export default {
  data () {
    // 验证是否选择角色
    var checkSelect = (rule, value, cb) => {
      console.log(value)
      // 验证角色选择是否选择
      if (value == '') {
        return cb(new Error('请选择角色'))
      } else {
        return cb()
      }
    }
    // 验证手机号的自定义规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regmobile = /^((\(\d{2,3}\))|(\d{3}\\-))?1(3|5|8|9)\d{9}$/
      if (regmobile.test(value)) {
        return cb()
      } else {
        cb(new Error('请输入正确的手机号'))
      }
    }
    return {
      // 获取用户列表的参数
      queryInfo: {
        query: '',
        // 当前页码
        pagenum: 1,
        pagesize: 5,
      },
      roleIdList: [
        {
          id: 1,
          name: '管理员',
          value: 888,
        },
        {
          id: 2,
          name: '普通用户',
          value: 1,
        },
        {
          id: 3,
          name: '维修员',
          value: 2,
        },
      ],
      // 用户列表数据
      userList: [],
      total: 0,
      // 控制对话框的显示和隐藏
      addDialogVisble: false,
      // 添加用户表单数据
      addForm: {
        name: '',
        password: '',
        email: '',
        mobile: '',
      },
      // 添加用户表单的验证规则
      addFormRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度为3~10个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '用户名长度为6~15个字符',
            trigger: 'blur',
          },
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'blur' },
          { validator: checkSelect, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' },
        ],
      },
      // 控制修改用户对话框的显示和隐藏
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      editRoldName: '', //修改用户的时候的角色Id的名字
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      await getAllUser(
        this.queryInfo.pagenum,
        this.queryInfo.pagesize,
        this.queryInfo.query
      ).then((res) => {
        if (res.data.code == 0) {
          this.userList = res.data.data.list
          this.total = res.data.data.total
        } else {
          return this.$message.error('获取用户数据失败')
        }
      })
    },
    // 监听每页显示条数的函数
    handleSizeChange (newSize) {
      console.log(newSize)
      this.queryInfo.pagesize = newSize
      // 重新获取用户列表数据
      this.getUserList()
    },
    // 监听页码的函数
    handleCurrentChange (newPage) {
      console.log(newPage)
      this.queryInfo.pagenum = newPage
      // 重新获取用户列表数据
      this.getUserList()
    },
    // 监听状态按钮的改变
    async setting_state (userinfo) {
      console.log(userinfo)
      await modify(userinfo.id, null, null, null, userinfo.state).then(
        (res) => {
          if (res.data.code == 0) {
            this.$message.success('更新用户状态成功')
          } else {
            userinfo.mg_state = !userinfo.mg_state
            return this.$message.error('用户状态更新失败')
          }
        }
      )
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户点击确定
    addUses () {
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) {
        } else {
          // 通过验证，进行请求添加操作
          await register(
            this.addForm.name,
            this.addForm.password,
            this.addForm.phone,
            this.addForm.roleId
          ).then((res) => {
            if (res.data.code == 0) {
              this.$message.success('添加用户成功')
              this.addDialogVisble = false
              // 重新获取用户列表
              this.getUserList()
            } else {
              return this.$message.error('添加用户失败')
            }
          })
        }
      })
    },
    // 展示编辑用户对话框
    async showeditDialog (id) {
      // console.log(id)
      await getInfo(id).then((res) => {
        if (res.data.code == 0) {
          this.editForm = res.data.data
          if (this.editForm.roleId == 1) {
            this.editRoldName = '普通用户'
          } else if (this.editForm.roleId == 2) {
            this.editRoldName = '维修员'
          } else if (this.editForm.roleId == 888) {
            this.editRoldName = '管理员'
          } else {
            this.editRoldName = '超级管理员'
          }
          console.log(this.editForm)
        } else {
          return this.$message.error('查询用户信息失败')
        }
      })
      this.editDialogVisible = true
    },
    // 监听用户修改对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改后的用户信息
    editUser () {
      // console.log(id)
      this.$refs.editFormRef.validate(async (valid) => {
        console.log(valid)
        if (!valid) {
        } else {
          if (
            this.editRoldName == 1 ||
            this.editRoldName == 2 ||
            this.editRoldName == 888 ||
            this.editRoldName == 999
          ) {
            this.editForm.roleId = this.editRoldName
          }
          modify(
            this.editForm.id,
            null,
            this.editForm.phone,
            this.editForm.roleId
          ).then((res) => {
            if (res.data.code == 0) {
              this.editDialogVisible = false
              this.getUserList()
              this.$message.success('更新用户信息成功')
            } else {
              this.$message.error('更新用户信息失败')
            }
          })
        }
      })
    },
    // 删除用户
    async deleteuser (id) {
      console.log(id)
      const res = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 用户确认删除  返回值为confirm
      // 用户取消删除  返回值为cancel
      if (res === 'cancel') {
        this.$message.info('已取消删除该用户')
      } else {
        await deleteUser(id).then((res) => {
          if (res.data.code == 0) {
            this.$message.success('已删除该用户')
            this.getUserList()
          } else {
            return this.$message.error('用户删除失败')
          }
        })
      }
    },
    // 重置密码
    async setPwd (id) {
      const res = await this.$confirm(
        '此操作将重置该用户的密码为初始密码, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // 用户确认重置  返回值为confirm
      // 用户取消重置  返回值为cancel
      if (res === 'cancel') {
        this.$message.info('已取消重置该用户密码')
      } else {
        modify(this.resetPwdId, 123456, null, null, null).then((res) => {
          if (res.data.code == 0) {
            this.$message.success('重置密码成功')
            this.setPwdDialogVisible = false
          } else {
            this.$message.error('重置密码失败')
          }
        })
      }
    },
  },
}
</script>
<style scoped>
.box-card_head {
  margin-bottom: 15px;
}
.el-select {
  width: 100%;
}
.resetPws >>> .el-dialog__body {
  padding: 2px 20px;
}
.resetPws >>> .el-dialog__footer {
  padding: 0px 20px 10px;
}
</style>